package com.boarsoft.boar.common.auth;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.auth.TokenAuth;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.boar.common.Logon;
import com.boarsoft.boar.context.ActionContext;
import com.boarsoft.boar.sys.SysPowerBiz;
import com.boarsoft.boar.sys.SysUserBiz;
import com.boarsoft.boar.sys.entity.SysFunc;
import com.boarsoft.boar.sys.entity.SysUser;
import com.boarsoft.cache.Cache;
import com.boarsoft.common.Util;
import com.boarsoft.common.util.BeanUtil;

/**
 * 权限检查
 * 
 * @author Mac_J
 *
 */
// @Component("tokenAuth")
public class BasicTokenAuthImpl implements TokenAuth {
	protected static final Logger log = LoggerFactory.getLogger(BasicTokenAuthImpl.class);

	@Autowired
	private SysPowerBiz sysPowerBiz;
	@Autowired
	private SysUserBiz sysUserBiz;

	@Override
	public ReplyInfo<Object> check(String token, String module) {
		// String uid = sysPowerBiz.checkToken(token);// 此方法返回用户ID
		// if (Util.strIsEmpty(uid)) {
		// log.warn("Token {} is invalid", token);
		// return new ReplyInfo<Object>(false, "Token is invalid");
		// }
		SysUser uo = sysPowerBiz.getUserByToken(token);
		if (uo == null) {
			log.warn("Token {} is invalid", token);
			return new ReplyInfo<Object>("Token is invalid");
		}
		Logon lg = uo.toLogon();
		// 如果模块编号为空，表示不检查模块权限，仅注入token和logon
		if (Util.strIsEmpty(module)) {
			return new ReplyInfo<Object>(true, lg);
		}
		if (sysPowerBiz.check(uo.getId(), module)) {
			return new ReplyInfo<Object>(true, lg);
		}
		log.warn("Reject {} access {}", uo.getId(), module);
		return new ReplyInfo<Object>("Access unauthorized");
	}

	@Override
	public ReplyInfo<Object> check(String token) throws Exception {
		if (Util.strIsEmpty(token)) {
			return Constants.REPLY_WARN_INVALID;
		}
		Logon lg = null;
		Cache cache = ActionContext.getCache();
		if (cache != null) {
			try {
				lg = (Logon) cache.get("token", token);
			} catch (Exception e) {
				log.error("Error on get logon from cache with token {}", token, e);
			}
		}
		if (lg == null) {
			SysUser uo = sysPowerBiz.getUserByToken(token);
			if (uo == null) {
				log.warn("Token {} is invalid", token);
				return new ReplyInfo<Object>("Token is invalid");
			}
			// 生成Logon对象
			lg = uo.toLogon();
			// 查询用户拥有的所有权限
			List<SysFunc> funcs = sysPowerBiz.getMyFuncs(lg.getId(), null);
			for (SysFunc f : funcs) {
				f.setRoles(null);
				SysFunc a = BeanUtil.transfer(f, SysFunc.class);
				lg.getFuncs().add(a);
			}
			// 放入缓存
			log.info("Put user/token {}/{} to cache", lg.getId(), token);
			if (cache != null) {
				cache.put("token", token, lg);
			}
		}
		return new ReplyInfo<Object>(true, lg);
	}

	@Override
	public void logout(String uid, String token) {
		sysUserBiz.logout(uid);
		Cache cache = ActionContext.getCache();
		if (cache != null && Util.strIsNotEmpty(token)) {
			try {
				cache.remove("token", token);
			} catch (UnsupportedEncodingException e) {
				log.error("Error on remove token", e);
			}
		}
	}
}